from django.db import models
from django.contrib.auth.models import User
from django.conf import settings


class TextGenerationRecord(models.Model):
    """文本生成记录表"""
    
    # 模块类型
    MODULE_CHOICES = [
        ('creative', '智能写作'),
        ('academic', '学术写作辅助'),
    ]
    
    # 内容类型
    CONTENT_TYPE_CHOICES = [
        # 智能写作类型
        ('novel', '小说'),
        ('poetry', '诗歌'),
        ('script', '剧本'),
        ('story', '故事'),
        ('copy', '文案'),
        # 学术写作类型
        ('paper', '论文'),
        ('summary', '摘要'),
        ('reference', '参考文献'),
        ('report', '研究报告'),
    ]
    
    # 语言风格
    LANGUAGE_STYLE_CHOICES = [
        ('casual', '随意'),
        ('formal', '正式'),
        ('professional', '专业'),
        ('creative', '创意'),
        ('academic', '学术'),
        ('poetic', '诗意'),
        ('humorous', '幽默'),
        ('serious', '严肃'),
    ]
    
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='用户', null=True, blank=True)
    module = models.CharField(max_length=20, choices=MODULE_CHOICES, verbose_name='功能模块')
    content_type = models.CharField(max_length=20, choices=CONTENT_TYPE_CHOICES, verbose_name='内容类型')
    language_style = models.CharField(max_length=20, choices=LANGUAGE_STYLE_CHOICES, verbose_name='语言风格', default='casual')
    prompt = models.TextField(verbose_name='提示词')
    generated_content = models.TextField(verbose_name='生成内容', blank=True)
    generation_params = models.JSONField(verbose_name='生成参数', default=dict, blank=True)
    used_model = models.CharField(max_length=100, verbose_name='使用模型', default='doubao-1.5-pro')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='生成时间')
    is_favorite = models.BooleanField(default=False, verbose_name='是否收藏')
    
    class Meta:
        verbose_name = '文本生成记录'
        verbose_name_plural = '文本生成记录'
        ordering = ['-created_at']
        db_table = 'ai_text_generation_record'
    
    def __str__(self):
        return f'{self.get_module_display()} - {self.get_content_type_display()}'
    
    def prompt_preview(self):
        """提示词预览（前50字）"""
        return self.prompt[:50] + '...' if len(self.prompt) > 50 else self.prompt
    prompt_preview.short_description = '提示词预览'
    
    def content_preview(self):
        """生成内容预览（前100字）"""
        if not self.generated_content:
            return "暂无内容"
        return self.generated_content[:100] + '...' if len(self.generated_content) > 100 else self.generated_content
    content_preview.short_description = '生成内容预览'
    
    def get_current_model(self):
        """获取当前配置的模型"""
        return getattr(settings, 'ARK_TEXT_MODEL_ID', 'doubao-seed-1-6-vision-250815')
    
    def save(self, *args, **kwargs):
        """保存时自动设置使用的模型"""
        if not self.used_model:
            self.used_model = self.get_current_model()
        super().save(*args, **kwargs)


class PromptTemplate(models.Model):
    """提示词模板模型"""
    
    content_type = models.CharField(max_length=20, choices=TextGenerationRecord.CONTENT_TYPE_CHOICES, verbose_name='内容类型')
    language_style = models.CharField(max_length=20, choices=TextGenerationRecord.LANGUAGE_STYLE_CHOICES, default='casual', verbose_name='语言风格')
    template = models.TextField(verbose_name='提示词模板')
    is_active = models.BooleanField(default=True, verbose_name='是否启用')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        verbose_name = '提示词模板'
        verbose_name_plural = '提示词模板'
        db_table = 'ai_text_prompt_template'
        # 添加唯一约束，确保同一内容类型和语言风格的组合是唯一的
        unique_together = ('content_type', 'language_style')
    
    def __str__(self):
        return f'{self.get_content_type_display()} - {self.get_language_style_display()} - 提示词模板'
